package com.auto.netty.codec;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

//自定义处理器类，继承Netty的HandlerAdapter(处理器规范)
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 读取数据事件，读取客户端发送的消息
     *
     * @param ctx 上下文对象，包含管道pipeline和通道channel
     * @param msg 客户端发送的消息
     * @throws Exception
     */
    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        StudentPOJO.Student student = (StudentPOJO.Student) msg;
        System.out.println("客户端发送的Student对象，id = " + student.getId() + " name = " + student.getName());
    }

    /**
     * 数据读取完成后，给客户端响应数据
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello，客户端-1", CharsetUtil.UTF_8));
    }

    /**
     * 处理异常，一般是关闭通道
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
